package 锁;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhang lei
 * @Date 2021-10-28 11:05
 */
public class ThreadLifeStyle {

    public static void main(String[] args) throws InterruptedException {
        List<Integer> list = new ArrayList<>(100);
        WorkA workA = new WorkA(list);
        WorkB workB = new WorkB(list);
        new Thread(workA, "one").start();
        new Thread(workB, "two").start();
    }


}

class TestObject{

}

class WorkA implements Runnable{

    private List<Integer> list;

    public WorkA(List<Integer> list) {
        this.list = list;
    }

    @Override
    public void run() {
        synchronized (list) {
            try {
                //wait释放锁，进入等待池，等待被notify然后进行竞争
                System.out.println("A 第一次添加");
                for (int i = 0; i < 20; i++) {
                    list.add(i);
                }

                list.wait();

                System.out.println("A第二次添加");
                for (int i = 0; i < 50; i++) {
                    list.add(i);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("A:"+Thread.currentThread().getId()+ "————this is WorkA");

        }
    }
}

class WorkB implements Runnable{

    private List<Integer> list;

    public WorkB(List<Integer> list) {
        this.list = list;
    }

    @Override
    public void run() {
        synchronized (list) {
            System.out.println("B: "+Thread.currentThread().getId()+ "————this is WorkB");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while (list.size()>0) {
                for (Integer integer : list) {
                    System.out.println(integer);
                }
                list.clear();
                //notifyAll唤醒在这个，进入等待池，等待被notify然后进行竞争
            }
            list.notifyAll();
        }
        Thread.yield();
        synchronized (list) {
            while (list.size()>0) {
                for (Integer integer : list) {
                    System.out.println(integer);
                }
                list.clear();
            }
        }
    }
}
